package com.matrix.product.listener;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.matrix.common.constant.RocketMQConstants;
import com.matrix.product.entity.Product;
import com.matrix.product.mapper.ProductMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 有点甜
 * @since 2025/8/5
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = RocketMQConstants.PRODUCT_STOCK_DEDUCT_TOPIC,
        consumerGroup = RocketMQConstants.PRODUCT_STOCK_DEDUCT_CONSUMER_GROUP
)
public class StockDeductListener implements RocketMQListener<Map<Long, Integer>> {

    private final ProductMapper productMapper;

    @Override
    public void onMessage(Map<Long, Integer> stockDeductionMap) {
        log.info("收到异步更新数据库库存消息: {}", stockDeductionMap);
        try {
            for (Map.Entry<Long, Integer> entry : stockDeductionMap.entrySet()) {
                int updatedRows = productMapper.update(null,
                        new LambdaUpdateWrapper<Product>()
                                .eq(Product::getId, entry.getKey())
                                .ge(Product::getStock, entry.getValue())
                                .setSql("stock = stock - " + entry.getValue())
                );
                if (updatedRows == 0) {
                    log.error("异步扣减数据库库存失败,ProductId: {}, Quantity: {}", entry.getKey(), entry.getValue());
                }
            }
        } catch (Exception e) {
            log.error("处理异步更新库存消息失败", e);
            throw new RuntimeException("Failed to update stock in DB", e);
        }
    }
}
